//
//  CONewserRechargeAlert.swift
//  CocoProject
//
//  Created by Vill on 2023/11/16.
//

import UIKit
import AVFoundation

typealias certainBlock = ()->Void
class CONewserRechargeAlert: COBaseAlertView {

    var callBolck:certainBlock?
    var player = AVPlayer()
    var playerLayer = AVPlayerLayer()
    
    init(with walletModel:COBalanceModel) {
        super.init(type: .Center)
        NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil,userInfo: ["type":1])
        self.contentWidth = PTW(350)
        self.contentView?.backgroundColor = UIColor.white
        self.contentView?.layer.borderColor = UIColor.clear.cgColor
        self.contentView?.layer.cornerRadius = PTW(10)
        
        self.contentView?.addSubview(self.videoView)
        self.contentView?.addSubview(self.bgVideoImg)
        self.contentView?.addSubview(self.bottomView)
        self.contentView?.addSubview(self.priceImg)
        self.contentView?.addSubview(self.priceLbl)
        self.contentView?.addSubview(self.origalLbl)
        self.contentView?.addSubview(self.goBtn)
        self.contentView?.addSubview(self.countLbl)
        self.videoView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(self.contentWidth)
            make.height.equalTo(PTW(480))
            make.bottom.equalToSuperview()
        }
        self.bgVideoImg.snp.makeConstraints { make in
            make.edges.equalTo(self.videoView)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(PTW(150))
        }
        self.priceImg.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(90), PTW(36)))
            make.left.equalToSuperview().offset(PTW(10))
            make.bottom.equalToSuperview().offset(-PTW(27))
        }
        self.priceLbl.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(self.priceImg)
        }
        self.origalLbl.snp.makeConstraints { make in
            make.centerY.equalTo(self.priceImg)
            make.left.equalTo(self.priceImg.snp.right).offset(PTW(7.5))
        }
        self.countLbl.snp.makeConstraints { make in
            make.bottom.equalTo(self.priceImg.snp.top).offset(-PTW(5))
            make.left.equalToSuperview().offset(PTW(10))
        }
        self.goBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(90), PTW(90)))
            make.bottom.equalTo(self.priceImg)
            make.right.equalToSuperview().offset(-PTW(10))
        }
        self.countLbl.text = "\(walletModel.real + walletModel.free)Coins"
        self.priceLbl.text = String(format: "$%.2f", walletModel.price)
        
        var staticStar = ""
        if (kStaticStartStr.keyGetNSDefaultsKey() != nil){
            let launchStatic = kStaticStartStr.keyGetNSDefaultsKey() as! String
            let staticArr = launchStatic.components(separatedBy: ",")
            if staticArr.count >= 2{
                staticStar = staticArr[2]
            }
            let videoUrl = URL(string: staticStar)
            // 在后台线程执行耗时任务
            DispatchQueue.main.safeAsync {
                self.player = AVPlayer(url: videoUrl!)
                self.player.volume = 0
                self.playerLayer = AVPlayerLayer(player: self.player)
                self.playerLayer.frame = CGRectMake(0, 0, self.contentWidth, PTW(480))
                self.playerLayer.videoGravity = .resizeAspectFill
                self.bgVideoImg.layer.addSublayer(self.playerLayer)
                self.bgVideoImg.layer.insertSublayer(self.playerLayer, at: 2)
                self.player.play()
            }
            NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(avPlayerItemDidPlayToEndTime), name: .AVPlayerItemDidPlayToEndTime, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        DispatchQueue.main.safeAsync {
            self.countLbl.textColor = UIColor.gradientFromColor(colors: [UIColor.colorWithHex("#FFE65F").cgColor,UIColor.colorWithHex("#FD1717").cgColor], direction: .Vertical, range: self.countLbl.bounds.size.height)
            self.bottomView.backgroundColor = UIColor.gradientFromColor(colors: [UIColor.colorWithHex("#000000", 0).cgColor,UIColor.colorWithHex("#000000", 0.1).cgColor], direction: .Vertical, range: PTW(150))
        }
    }
    
    lazy var countLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.pingfangFont(ofSize: 43, weight: .semibold)
        return lbl
    }()
    
    lazy var priceLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.pingfangFont(ofSize: 22, weight: .semibold)
        lbl.textColor = .white
        return lbl
    }()
    
    lazy var origalLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.pingfangFont(ofSize: 17, weight: .regular)
        lbl.textColor = .white
        let str = NSMutableAttributedString(string: "$3.99")
        str.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: NSMakeRange(0, str.length))
        lbl.attributedText = str
        return lbl
    }()
    
    lazy var priceImg: UIImageView = {
        let img = UIImageView()
        img.image = KImaged("coco_newuser_priceBg")
        return img
    }()
    
    lazy var goBtn: UIButton = {
        let img = UIButton(type: .custom)
        img.setImage(KImaged("coco_newuser_goBtn"), for: .normal)
        img.addTarget(self, action: #selector(goBtnAction), for: .touchUpInside)
        return img
    }()
    
    lazy var videoView: UIView = {
        let img = UIView()
        img.backgroundColor = .clear
        img.layer.cornerRadius = PTW(10)
        img.layer.masksToBounds = true
        return img
    }()
    
    lazy var bgVideoImg: UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFill
        img.layer.masksToBounds = true
        return img
    }()
    
    lazy var bottomView: UIView = {
        let img = UIView()
        return img
    }()
    
    func getFrameFromVideo(url: URL, timeInSeconds: Float64) -> UIImage? {
        let asset = AVAsset(url: url)
        let imageGenerator = AVAssetImageGenerator(asset: asset)
        imageGenerator.appliesPreferredTrackTransform = true
        let time = CMTime(seconds: timeInSeconds, preferredTimescale: 600)
        var frameImage: UIImage?
        do {
            let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
            frameImage = UIImage(cgImage: cgImage)
        } catch {
            print("Error generating frame image: \(error)")
        }
        return frameImage
    }
    
    @objc func goBtnAction(){
        dissMiss()
        if self.callBolck != nil{
            self.callBolck!()
        }
    }
    
    @objc private func applicationDidBecomeActive(noti: Notification) {
        self.player.play()
    }

    @objc private func applicationWillResignActive(noti: Notification) {
        self.player.pause()
    }

    @objc private func avPlayerItemDidPlayToEndTime(noti: Notification) {
        self.player.seek(to: CMTime(value: 0, timescale: 1))
        self.player.play()
    }

}
